<template>
  <div>
    <div ref="googleSignInButton"></div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'

const googleSignInButton = ref(null)
const error = ref(null)


const handleCredentialResponse = async (response) => {
  try {
    const token = response.credential
    const res = await axios.post('http://localhost:3000/auth/google', { token })
    if (res.data.success) {
      localStorage.setItem('user', JSON.stringify(res.data.user))
      localStorage.setItem('token', res.data.token)
      alert('登录成功')
      
    } else {
      error.value = '登录失败，请重试'
    }
  } catch (err) {
    error.value = '登录失败，请重试'
    console.error('登录错误:', err)
  }
}

const initializeGoogleSignIn = () => {
  const script = document.createElement('script')
  script.src = 'https://accounts.google.com/gsi/client'
  script.async = true
  script.defer = true
  document.head.appendChild(script)

  script.onload = () => {
    window.google.accounts.id.initialize({
      client_id: '',
      callback: handleCredentialResponse,
      auto_select: false,
      cancel_on_tap_outside: false
    })

    window.google.accounts.id.renderButton(
      googleSignInButton.value,
      {
        type: 'standard',
        theme: 'outline',
        size: 'large',
        text: 'signin_with',
        shape: 'rectangular',
        logo_alignment: 'left'
      }
    )
  }
}

onMounted(() => {
  initializeGoogleSignIn()
})

onUnmounted(() => {
  const script = document.querySelector('script[src="https://accounts.google.com/gsi/client"]')
  if (script) {
    document.head.removeChild(script)
  }
})
</script>

<style scoped>
</style>
